package com.cat.dataStructure03;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/decremental-string-concatenation/
 * @create 2025/11/18 18:53
 * @since JDK17
 */

public class Solution87 {
    String[] words;
    Map<String, Integer> map = new HashMap<>();
    int dfs(int i, char l, char r) {
        if (i == words.length - 1) {
            return 0;
        }
        String key = i + "," + l + "," + r;
        if (map.containsKey(key)) {
            return map.get(key);
        }
        i++;
        int ans = 0, len = words[i].length();
        ans = Math.min(
                dfs(i, words[i].charAt(0), r) + len - (words[i].charAt(len - 1) == l ? 1 : 0),
                dfs(i, l, words[i].charAt(len - 1)) + len - (words[i].charAt(0) == r ? 1 : 0)
        );
        map.put(key, ans);
        return ans;
    }
    public int minimizeConcatenatedLength(String[] words) {
        this.words = words;
        return dfs(0, words[0].charAt(0), words[0].charAt(words[0].length() - 1)) + words[0].length();
    }
}
